package main

import (
	"os"
	"path/filepath"

	"gopkg.in/yaml.v3"
)

type Config struct {
	DBPath         string `json:"dbPath" yaml:"db-path"`
	AttachmentPath string `json:"attachmentPath" yaml:"attachment-path"`
}

var globalConfig *Config

func GetConfigPath() string {
	homeDir, _ := os.UserHomeDir()
	return filepath.Join(homeDir, ".config", "idea-note", "config.yml")
}

func GetAbsPath(path string) string {
	if path == "" {
		return ""
	}
	if path[0] == '~' {
		homeDir, _ := os.UserHomeDir()
		return filepath.Join(homeDir, path[1:])
	}
	return path
}

func InitConfigInfo() error {
	configPath := GetConfigPath()
	// 判断文件是否存在
	_, err := os.Stat(configPath)
	if err != nil {
		err = generateInitConfig()
		if err != nil {
			return err
		}
	}

	b, err := os.ReadFile(configPath)
	if err != nil {
		return err
	}
	var config Config
	err = yaml.Unmarshal(b, &config)
	if err != nil {
		return err
	}

	globalConfig = &config
	return nil
}

const configContent = `db-path: ~/.config/idea-note/idea-note.db
attachment-path: ~/.config/idea-note/attachment
`

func generateInitConfig() error {
	configPath := GetConfigPath()
	err := os.MkdirAll(filepath.Dir(configPath), os.ModePerm)
	if err != nil {
		return err
	}
	configFile, err := os.Create(configPath)
	if err != nil {
		return err
	}

	_, err = configFile.WriteString(configContent)
	if err != nil {
		return err
	}

	return nil
}
